<template>
  <div class="merchant-layout">
    <!-- 固定侧边栏 -->
    <el-aside width="200px">
      <el-menu
        :default-active="activeMenu"
        class="el-menu-vertical"
        router
        background-color="#304156"
        text-color="#bfcbd9"
        active-text-color="#409EFF"
      >
        <!-- 删除控制台菜单项 -->
        <!-- <el-menu-item index="/merchant/dashboard">
          <el-icon><Menu /></el-icon>
          <span>控制台</span>
        </el-menu-item> -->
        <el-menu-item index="/merchant/products">
          <el-icon><Goods /></el-icon>
          <span>商品管理</span>
        </el-menu-item>
        <el-menu-item index="/merchant/orders">
          <el-icon><List /></el-icon>
          <span>订单管理</span>
        </el-menu-item>
        <el-menu-item index="/merchant/promotions">
          <el-icon><Discount /></el-icon>
          <span>促销活动</span>
        </el-menu-item>
        <el-menu-item index="/merchant/statistics">
          <el-icon><DataLine /></el-icon>
          <span>经营数据</span>
        </el-menu-item>
        <el-menu-item index="/merchant/users">
          <el-icon><User /></el-icon>
          <span>用户分析</span>
        </el-menu-item>
      </el-menu>
    </el-aside>

    <!-- 固定头部 -->
    <el-header>
      <div class="header-container">
        <div class="logo">拼刀刀商家后台</div>
        <div class="user-info">
          <el-button type="primary" size="small" @click="openChangePasswordDialog">修改密码</el-button>
          <el-button type="text" class="logout-button" @click="confirmLogout">退出登录</el-button>
        </div>
      </div>
    </el-header>

    <!-- 可滚动的主内容区域 -->
    <el-main>
      <router-view />
    </el-main>

    <!-- 修改密码对话框 -->
    <el-dialog
      title="修改密码"
      v-model="passwordDialogVisible"
      width="30%"
    >
      <el-form :model="passwordForm" :rules="passwordRules" ref="passwordFormRef" label-width="100px">
        <el-form-item label="原密码" prop="oldPassword">
          <el-input v-model="passwordForm.oldPassword" type="password" show-password />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="passwordForm.newPassword" type="password" show-password />
        </el-form-item>
        <el-form-item label="确认新密码" prop="confirmPassword">
          <el-input v-model="passwordForm.confirmPassword" type="password" show-password />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="passwordDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="changePassword">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, ref, reactive, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useMerchantStore } from '@/store/merchant'
import { ElMessageBox, ElMessage } from 'element-plus'
import { updatePassword } from '@/api/merchant'
import type { FormInstance, FormRules } from 'element-plus'
import { Goods, Discount, DataLine, User, Menu, List } from '@element-plus/icons-vue'

interface MerchantInfo {
  name?: string;
  username?: string;
  [key: string]: any; // 允许其他属性
}

const router = useRouter()
const route = useRoute()
const merchantStore = useMerchantStore()

const activeMenu = computed(() => {
  return route.path
})

// 商家信息
const merchantInfo = computed<MerchantInfo>(() => {
  return merchantStore.merchantInfo as MerchantInfo
})

// 修改密码对话框
const passwordDialogVisible = ref(false)
const passwordFormRef = ref<FormInstance>()
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 密码表单验证规则
const passwordRules = reactive<FormRules>({
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度必须在6-20之间', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度必须在6-20之间', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度必须在6-20之间', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
})

// 打开修改密码对话框
const openChangePasswordDialog = () => {
  passwordForm.oldPassword = ''
  passwordForm.newPassword = ''
  passwordForm.confirmPassword = ''
  passwordDialogVisible.value = true
}

// 修改密码
const changePassword = async () => {
  if (!passwordFormRef.value) return

  await passwordFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 调用API修改密码
        await updatePassword({
          oldPassword: passwordForm.oldPassword,
          newPassword: passwordForm.newPassword
        })

        ElMessage.success('密码修改成功')
        passwordDialogVisible.value = false
      } catch (error) {
        console.error('修改密码失败:', error)
        ElMessage.error('修改密码失败，请稍后重试')
      }
    }
  })
}

// 获取商家信息
onMounted(async () => {
  if (Object.keys(merchantInfo.value).length === 0) {
    await merchantStore.getMerchantInfo()
  }
})

// 监听路由变化，重置滚动位置
watch(() => route.path, () => {
  // 确保主内容区域滚动到顶部
  document.querySelector('.el-main')?.scrollTo({
    top: 0,
    behavior: 'instant'
  })
})

// 确认退出登录
const confirmLogout = () => {
  ElMessageBox.confirm('确定要退出登录吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    merchantStore.logout()
  }).catch(() => {})
}
</script>

<style scoped>
.merchant-layout {
  height: 100vh;
  position: relative;
}

.el-header {
  background-color: #fff;
  color: #333;
  line-height: 60px;
  border-bottom: 1px solid #e6e6e6;
  position: fixed; /* 固定头部 */
  width: calc(100% - 200px); /* 减去侧边栏宽度 */
  top: 0;
  left: 200px; /* 侧边栏宽度 */
  right: 0;
  z-index: 10;
  height: 60px;
}

.header-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
}

.logo {
  font-size: 18px;
  font-weight: bold;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 15px;
}

.welcome-text {
  color: #333;
  font-size: 14px;
}

.logout-button {
  color: #409EFF;
  font-size: 14px;
  padding: 0;
  margin-left: 10px;
}

.logout-button:hover {
  color: #66b1ff;
  text-decoration: underline;
}

.el-aside {
  background-color: #304156;
  color: #bfcbd9;
  position: fixed; /* 固定侧边栏 */
  left: 0;
  top: 0;
  bottom: 0;
  width: 200px !important; /* 确保宽度固定 */
  z-index: 20;
  overflow-y: auto; /* 如果菜单项过多，允许滚动 */
}

.el-menu {
  border-right: none;
  height: 100%;
}

.el-main {
  background-color: #f0f2f5;
  padding: 20px;
  margin-left: 200px; /* 为侧边栏留出空间 */
  margin-top: 60px; /* 为头部留出空间 */
  min-height: calc(100vh - 60px); /* 减去头部高度 */
  overflow-y: auto; /* 允许内容区域滚动 */
  box-sizing: border-box;
  position: relative; /* 确保定位正确 */
}
</style>




